package com.heima.admin.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdLoginMapper;
import com.heima.admin.service.AdLoginService;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class AdLoginServiceImpl extends ServiceImpl<AdLoginMapper, AdUser> implements AdLoginService {
    @Override
    public ResponseResult loginIN(AdUserDTO adUserDTO) {
        // 1 参数校验
        if (StringUtils.isEmpty(adUserDTO.getName()) || StringUtils.isEmpty(adUserDTO.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 根据用户名查询用户信息
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDTO.getName()));
        //2.1 判断用户是否存在
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (9 != user.getStatus().intValue()) {

            CustomException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "用户状态异常,请联系管理员");
        }
        //3 获取数据库密码和盐,匹配密码
        String salt = user.getSalt();
        String password = user.getPassword();

        //   使用工具类合成密文密码,并验证是否相同
        String newPwd = DigestUtils.md5DigestAsHex((adUserDTO.getPassword() + salt).getBytes());
        if (!password.equals(newPwd)) {
            CustomException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户名或密码错误");
        }
        // 4 密码相同,修改登录时间
        user.setLoginTime(new Date());
        //5 颁发token令牌,使用工具类AppJwtUtil
        String token = AppJwtUtil.getToken(user.getId().longValue());
        // 用户信息返回vo
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(user, adUserVO);
        //6 返回结果(jwt)
        Map map = new HashMap();
        map.put("token", token);
        map.put("user", adUserVO);

        return ResponseResult.okResult(map);

    }
}
